#include "Screen.h"

Screen* Screen::_instance=NULL;

/* The screen surface */
SDL_Surface* Screen::screen = NULL;


int maiorImagem(void* s1,void* s2);

Screen* Screen::instance(){
	if(Screen::_instance==NULL){
		Screen::_instance=new Screen();
	}
	return Screen::_instance;	
}

void Screen::init(unsigned int altura,unsigned int largura,bool fullscreen){

	/* Initialize SDL */
	if (SDL_Init (SDL_INIT_VIDEO) < 0){
		printf("Couldn't set  video mode\n");
		exit (1);
	}
	atexit (SDL_Quit);
	/* Set video mode */
	if(fullscreen){
		this->screen = SDL_SetVideoMode (altura,largura, 16,SDL_SWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
	}else
		this->screen = SDL_SetVideoMode (altura,largura, 16,SDL_SWSURFACE | SDL_DOUBLEBUF);

	if (this->screen == NULL){
		exit (2);
	}
}

void Screen::inscreveSurface(Imagem* s){
	this->allImagens.insereOrdem(s,maiorImagem);
}

void Screen::desInscreveSurface(Imagem* s){
	this->allImagens.retiraItemPorReferencia(s);
}


void Screen::update(unsigned long elapsedTime){ }

void Screen::draw(){
	SDL_Rect dest;
	Imagem* actual;
	SDL_Rect dstrect;

	dstrect.x=0;
	dstrect.y=0;
	dstrect.w=this->screen->w;
	dstrect.h=this->screen->h;

	SDL_FillRect(this->screen, &dstrect, 0);

	this->allImagens.resetIterador();
	while(this->allImagens.hasNext()){

		actual=(Imagem*)this->allImagens.getItem();

		if(actual!=NULL){
			if(actual->visivel()){
				dest.x =(Sint16)actual->getX() - (actual->getLargura()/2);
				dest.y =(Sint16)actual->getY() - (actual->getAltura()/2);

				SDL_BlitSurface(actual->getSurface(), NULL, this->screen, &dest);
			}
		}
		this->allImagens.nextIterador();
	}

	SDL_Flip(this->screen);
}





int maiorImagem(void* s1,void* s2){
	return ((Imagem*)s1)->getPrioridade() >
			((Imagem*)s2)->getPrioridade();
}


